package simonby.top.annualring.application.service;

import simonby.top.annualring.domain.model.User;
import simonby.top.annualring.domain.repository.UserRepository;
import simonby.top.annualring.infrastructure.repository.UserRepositoryImpl;
import simonby.top.annualring.infrastructure.security.PasswordEncryptionService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;

/**
 * 用户应用服务
 * 处理用户相关的业务逻辑
 */
@Service
public class UserApplicationService {
    private final UserRepository userRepository;
    private final PasswordEncryptionService passwordEncryptionService;

    public UserApplicationService(UserRepositoryImpl userRepository,
                                 PasswordEncryptionService passwordEncryptionService) {
        this.userRepository = userRepository;
        this.passwordEncryptionService = passwordEncryptionService;
    }

    /**
     * 创建用户
     * @param user 用户对象
     * @return 创建后的用户
     */
    public User createUser(User user) {
        // 对密码进行加密
        String encryptedPassword = passwordEncryptionService.encodePassword(user.getPassword());
        user.setPassword(encryptedPassword);
        return userRepository.save(user);
    }

    /**
     * 根据ID获取用户
     * @param id 用户ID
     * @return 用户对象
     */
    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }

    /**
     * 根据用户名获取用户
     * @param username 用户名
     * @return 用户对象
     */
    public Optional<User> getUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    /**
     * 获取所有用户
     * @return 用户列表
     */
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    /**
     * 更新用户
     * @param user 用户对象
     * @return 更新后的用户
     */
    public User updateUser(User user) {
        // 更新时如果密码有变化，则重新加密
        Optional<User> existingUser = userRepository.findById(user.getId());
        if (existingUser.isPresent() && 
            !passwordEncryptionService.matches(user.getPassword(), existingUser.get().getPassword())) {
            String encryptedPassword = passwordEncryptionService.encodePassword(user.getPassword());
            user.setPassword(encryptedPassword);
        }
        return userRepository.save(user);
    }

    /**
     * 删除用户
     * @param id 用户ID
     */
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }

    /**
     * 验证用户密码
     * @param rawPassword 原始密码
     * @param encodedPassword 加密密码
     * @return 是否匹配
     */
    public boolean validatePassword(String rawPassword, String encodedPassword) {
        return passwordEncryptionService.matches(rawPassword, encodedPassword);
    }

    /**
     * 验证用户登录
     * @param username 用户名
     * @param rawPassword 原始密码
     * @return 用户对象（如果验证成功）
     */
    public Optional<User> authenticate(String username, String rawPassword) {
        Optional<User> userOptional = userRepository.findByUsername(username);
        if (userOptional.isPresent()) {
            User user = userOptional.get();
            if (passwordEncryptionService.matches(rawPassword, user.getPassword())) {
                return Optional.of(user);
            }
        }
        return Optional.empty();
    }
}